//
//  PlayerViewController.m
//  自定义播放器
//
//  Created by dllo on 16/1/14.
//  Copyright © 2016年 dllo. All rights reserved.
//

#import "PlayerViewController.h"
#import <AVFoundation/AVFoundation.h>

@interface PlayerViewController ()
@property (weak, nonatomic) IBOutlet UIView *playerView;
// 开始按钮
@property (weak, nonatomic) IBOutlet UIButton *startButtoon;
- (IBAction)startAction:(id)sender;
// 用来控制进度的触发方法
- (IBAction)sliderAction:(id)sender;
// 用来修改内容的
@property (weak, nonatomic) IBOutlet UISlider *progressSlider;
// 假navigation
@property (weak, nonatomic) IBOutlet UIView *navigationView;
// 用来显示时间的
@property (weak, nonatomic) IBOutlet UILabel *timeLabel;
@property (weak, nonatomic) IBOutlet UIView *bottimView;

@property (nonatomic, strong)AVPlayer *player;
@property (nonatomic, strong)AVPlayerItem *playerItem;
@property (nonatomic, strong)AVPlayerLayer *plyerLayer;

@property (nonatomic, assign)BOOL isStart;
@property (nonatomic, assign)BOOL isTap;

// 用来记录视频播放时长
@property (nonatomic, assign)CGFloat duration;

@property (weak, nonatomic) IBOutlet UIView *bottomView;
@end

@implementation PlayerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.isStart = YES;
    self.progressSlider.value = 0;
//    [self.progressSlider addTarget:self action:@selector(addProgressSlide) forControlEvents:UIControlEventTouchUpInside | UIControlEventTouchCancel | UIControlEventTouchUpOutside];
    
    // 初始化播放器
    [self createPlayer];
    
    [self.player play];
    // 给当前屏幕,添加一个监听横竖屏和视频结束的方法
    [self addNotificationCenters];
    
    // 创建一个轻点的手势
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap:)];
    self.isTap = YES;
    self.playerView.userInteractionEnabled = YES;
    [self.playerView addGestureRecognizer:tap];

    
    // 对播放进度进行设置
    self.timeLabel.text = @"00:00/00:00";
    self.timeLabel.font = [UIFont systemFontOfSize:12];
    [self addProgress];

    
    
}

// CMTime是专门用来表示视频时间的
// CMTimeMake是用来创建CMTime的
// 用法就是CMTimeMake(time, timeScale)
// time指的是时间.但不是秒
// timeScale指的是1秒需要多少帧构成,而真正的时间是time/timeScale
#pragma mark 添加进度设置
//- (void)addProgressSlide {
//    // 设置成(1, 1), 毎1s执行一次
//    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
//        // 当前视频的总时间 , 将CMTime转换成CGFloat
//        CGFloat durationTime = CMTimeGetSeconds(self.playerItem.duration);
//        // 当前时间
//        CGFloat currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
//        // 倒计时
//        CGFloat rem = durationTime - currentTime;
//        
//        NSString *str = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d", (int)rem / 60, (int)rem % 60, (int)currentTime / 60, (int)currentTime % 60];
//        self.timeLabel.text = str;
//        
//        self.progressSlider.value = currentTime / durationTime;
//        // 保存总时长, 用于手动快进
//        self.duration = durationTime;
//    }];
//}

- (void)addProgress {
    // 设置成(1, 1), 毎1s执行一次
    [self.player addPeriodicTimeObserverForInterval:CMTimeMake(1, 1) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        // 当前视频的总时间 , 将CMTime转换成CGFloat
        CGFloat durationTime = CMTimeGetSeconds(self.playerItem.duration);
        // 当前时间
        CGFloat currentTime = CMTimeGetSeconds(self.playerItem.currentTime);
        // 倒计时
        CGFloat rem = durationTime - currentTime;
        
        NSString *str = [NSString stringWithFormat:@"%02d:%02d/%02d:%02d", (int)rem / 60, (int)rem % 60, (int)currentTime / 60, (int)currentTime % 60];
        self.timeLabel.text = str;
        
        self.progressSlider.value = currentTime / durationTime;
        // 保存总时长, 用于手动快进
        self.duration = durationTime;
    }];
}

#pragma mark 轻点触发
- (void)tap:(UITapGestureRecognizer *)tap {
    if (self.isTap == YES) {
        [UIView animateWithDuration:0.2 animations:^{
            self.bottomView.alpha = 0;
            self.navigationView.alpha = 0;
        }];
    } else {
        [UIView animateWithDuration:0.2 animations:^{
            self.bottomView.alpha = 1;
            self.navigationView.alpha = 1;
        }];
    }
    self.isTap = !self.isTap;
}

#pragma mark 添加监听方法
- (void)addNotificationCenters {
    // 监听当前视频播放情况,播放结束,触发方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    // 监听屏幕旋转
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(turnScreen:) name:UIApplicationDidChangeStatusBarOrientationNotification object:nil];
}

#pragma mark 播放结束
- (void)movieEnd:(NSNotification *)notification {
    [self dismissViewControllerAnimated:YES completion:^{
    }];
}

//#pragma mark 屏幕旋转
- (void)turnScreen:(NSNotification *)notification {
    UIInterfaceOrientation ori = [[UIApplication sharedApplication] statusBarOrientation];
    // 根据横竖屏调整播放器的frame
    if (ori == UIInterfaceOrientationLandscapeRight) {
        [self setPlayerLayerFrame];
    } else {
        [self setProFrame];
    }
}

- (void)setPlayerLayerFrame {
    self.plyerLayer.frame = CGRectMake(5, 5, WIDTH - 10, HEIGHT - 10);
}

- (void)setProFrame {
    self.plyerLayer.frame = CGRectMake(5, 5, WIDTH - 10, HEIGHT - 10);
}

#pragma mark 播放器创建
- (void)createPlayer {
    NSString *urlStr = self.playUrl;
    // 对网址进行转码
    urlStr =[urlStr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:urlStr];
    // 根据网址,创建视频项目对象
    self.playerItem = [[AVPlayerItem alloc] initWithURL:url];
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    // 创建一个播放器承载对象,把播放器放到上面
    self.plyerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    self.plyerLayer.frame = CGRectMake(5, 5, WIDTH - 10, HEIGHT - 10);
    // 视频的填充方式
    self.plyerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    // 把播放器添加到layer层上
    [self.playerView.layer insertSublayer:self.plyerLayer atIndex:0];
    [SVProgressHUD dismiss];
}

- (IBAction)startAction:(id)sender {
    if (self.isStart == YES) {
        [self.player pause];
        [self.startButtoon setImage:[UIImage imageNamed:@"btn_play@3x"] forState:UIControlStateNormal];
    } else {
        [self.player play];
        [self.startButtoon setImage:[UIImage imageNamed:@"btn_pause@3x"] forState:UIControlStateNormal];
    }
    self.isStart = !self.isStart;
}

- (IBAction)sliderAction:(id)sender {
    // 获取当前时间
    double currentTime = self.duration * self.progressSlider.value;
    CMTime drage = CMTimeMake(currentTime, 1);
    [self.player seekToTime:drage completionHandler:^(BOOL finished) {
        [self.player play];
    }];
}


- (void)viewWillDisappear:(BOOL)animated {
    [self.player pause];
}

#pragma mark - 强制横屏代码
- (BOOL)shouldAutorotate
{
    //是否支持转屏
    return NO;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations
{
    //支持哪些转屏方向
    return UIInterfaceOrientationMaskLandscape;
}

- (UIInterfaceOrientation)preferredInterfaceOrientationForPresentation
{
    return UIInterfaceOrientationLandscapeLeft;
}

- (BOOL)prefersStatusBarHidden
{
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
@end
